package com.atguigu.tingshu.order.context;


import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
//策略的管理类
public class OrderTradeStrategyContext implements ApplicationContextAware {

    //存储所有的策略对象
    private static final Map<String, OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<>();

    //根据付款的项目的类型获取对应的实现类对象
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        return ORDER_TRADE_STRATEGY_MAP.get(itemType) ;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        System.out.println(ORDER_TRADE_STRATEGY_MAP);

        /**
         * Map的键是bean的名称，值就是OrderTradeStrategy接口的实现类型对象
         */
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);

        beansOfType.values().stream().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();
            ORDER_TRADE_STRATEGY_MAP.put(itemType,orderTradeStrategy);
        });



    }
}
